import headerLess from "./index.module.less";

import { useSelector, useDispatch } from "react-redux";
import { showModal } from "@/store/modules/user";
import { fetchArticles } from "@/store/modules/searchArticle";
import UserInfoCard from "../userInfoCard";
import KeyTip from "./components/keyTip/KeyTip";
import Notice from "../notice";
import CreateTabs from "../createTabs";
import { useEffect, useState, useMemo, useRef } from "react";
import { Input } from "antd";
import { index } from "@/store/modules/index";
import useScrollbar from "@/hooks/useScrollbar";
import { debounce } from "@/utils/PublicFunction.ts";
import { GetKeyTipsListAPi } from "@/http/api/article";
import { useNavigate, useSearchParams, useLocation } from "react-router-dom";
import SearchPageTopTab from "./components/SearchPageTopTab/SearchPageTopTab";
import {
  SearchOutlined,
  CaretDownOutlined,
  CrownTwoTone,
} from "@ant-design/icons";

function Header() {
  const { noChangeHeaderRouterList } = useSelector((state: any) => state.index);

  const Tabs = [
    { id: 1, name: "首页", url: "/home" },
    { id: 2, name: "沸点", url: "/pins" },
    { id: 3, name: "课程" },
    { id: 4, name: "直播" },
    { id: 5, name: "活动" },
    { id: 6, name: "竞赛" },
    { id: 7, name: "商城" },
    { id: 8, name: "APP" },
    { id: 9, name: "插件" },
  ];
  const [width, setWidth] = useState("200px");
  const [getSearchArr] = useSearchParams();
  const [KeyTipsList, setKeyTipsList] = useState([]);
  const [showKeyTips, setShowKeyTips] = useState(false);
  const [SearchKey, SetSearchKey] = useState("");
  let SearchKeyRef = useRef("");

  const Scrollbar = useScrollbar().scrollDirection;
  const [createBtnShow, setCreateBtnShow] = useState(true);
  const accessToken = useSelector((state: any) => state.user.accessToken);
  const HeaderImg = useSelector((state: any) => state.user.HeaderImg);
  const username = useSelector((state: any) => state.user.username);
  const [TabId, setTabId] = useState(1);
  const dispatch = useDispatch();

  const location = useLocation();
  const pathname = location.pathname;
  const isNoChangeHeader = noChangeHeaderRouterList.some(
    (item: string) => pathname === item
  );
  const navigate = useNavigate();

  useEffect(() => {
    SearchKeyRef.current = SearchKey;
    console.log("变化更新55555555555", SearchKeyRef.current);
    debounce(GetKeyTipsList, 500)();
  }, [SearchKey]);

  const GetKeyTipsList = async () => {
    const params = {
      Filter: SearchKey,
    };
    const res: any = await GetKeyTipsListAPi(params);
    console.log("搜索结果", res);
    if (res.status === 0) {
      setKeyTipsList(res.KeyTipsList);
    }
  };

  const checkKey = () => {
    if (getSearchArr.getAll("SearchKey")[0]) {
      SetSearchKey(getSearchArr.getAll("SearchKey")[0]);
    }
  };

  useEffect(() => {
    checkKey();
  }, []);

  const onFocus = () => {
    setWidth(() => {
      return "330px";
    });
    setCreateBtnShow(() => {
      return false;
    });
    debounce(GetKeyTipsList, 500)();
    setShowKeyTips(() => true);
  };

  const handleInputChange = (e: any) => {
    SetSearchKey(() => {
      return e.target.value;
    });
    if (e.target.value == "") {
      setShowKeyTips(() => false);
    } else {
      setShowKeyTips(() => true);
    }
  };

  const onBlur = () => {
    setWidth(() => {
      return "200px";
    });
    setCreateBtnShow(() => {
      return true;
    });
    setShowKeyTips(() => false);
  };

  const onClickKeyTips = (item: string) => {
    console.log("更新", item);
    SearchKeyRef.current = item;
    SetSearchKey(() => item);
    SearchKeyMethods();
  };

  const SearchKeyMethods = () => {
    console.log("点击搜索", SearchKeyRef.current);
    dispatch(fetchArticles({ SearchKey: SearchKeyRef.current, type: 0 }));
    navigate("/searchPage?SearchKey=" + SearchKeyRef.current);
    /* navigate({
      pathname: "/searchPage",
      search: "?SearchKey=" + SearchKeyRef.current,
    }) */
  };
  const Toindex = () => {
    navigate("/");
  };

  const selectTab = (item: any) => {
    setTabId(() => item.id);
    navigate(item.url);
  };

  return (
    <>
      <div
        className={[
          headerLess.all_content_header,
          Scrollbar === "up" || isNoChangeHeader ? "" : headerLess.transformTop,
        ].join(" ")}
      >
        <div className="header_nei_content">
          <div className="left">
            <div className="logo" onClick={Toindex}>
              <img
                src="	https://lf3-cdn-tos.bytescm.com/obj/static/xitu_juejin_web/e08da34488b114bd4c665ba2fa520a31.svg"
                alt="稀土掘金logo"
              />
            </div>
          </div>
          <div className="center">
            {Tabs.map((item, index) => {
              return (
                <div
                  onClick={() => selectTab(item)}
                  className={[
                    TabId == item.id ? "tabsItem_active" : "",
                    "tabsItem",
                  ].join(" ")}
                  key={index}
                >
                  {item.name}
                </div>
              );
            })}
            <div className="tabsItem_te">
              <img
                src="../../../public/img/6ead6acfe4094ef7b541a6385b480157~tplv-k3u1fbpfcp-jj_115_0_0_0_q75.avis"
                alt="AI创意征文"
              />
            </div>
          </div>
          <div className="search_create_btn">
            <div className="header_input_content">
              <Input
                placeholder="探索稀土掘金"
                value={SearchKey}
                onChange={handleInputChange}
                onFocus={onFocus}
                onBlur={onBlur}
                style={{ width: width }}
              />
              <div className="header_search_btn" onMouseDown={SearchKeyMethods}>
                <SearchOutlined />
              </div>
            </div>
            {showKeyTips && KeyTipsList.length > 0 && (
              <div className="keytips">
                <KeyTip
                  KeyTipsList={KeyTipsList}
                  onClickTips={onClickKeyTips}
                />
              </div>
            )}
            <div
              className={[
                "header_create_article_btn",
                createBtnShow ? "" : "header_cab_none",
              ].join(" ")}
            >
              <div className="header_ca_title">创作者中心</div>
              <div style={{ flexShrink: 0 }}>
                <CreateTabs />
              </div>
              <div className="header_badge">有更新</div>
            </div>
          </div>
          <div className="header_vip">
            <CrownTwoTone style={{ fontSize: "18px" }} />
            <div className="header_vip_span">会员</div>
          </div>
          <div className="header_notice">
            <Notice />
          </div>
          <div className="right">
            {accessToken ? (
              <UserInfoCard headerImg={HeaderImg} username={username} />
            ) : (
              ""
            )}
            {!accessToken ? (
              <div className="login_btn" onClick={() => dispatch(showModal())}>
                注册 | 登录
              </div>
            ) : (
              ""
            )}
          </div>
        </div>
        {location.pathname === "/searchPage" && (
          <div className="bottom_tab">
            <SearchPageTopTab />
          </div>
        )}
      </div>
    </>
  );
}

export default Header;
